from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import db
from info.models import Category, News, User
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blue


# 实现指定用户的发布的新闻
@profile_blue.route('/other_news_list')
def other_news_list():
    """返回指定用户的发布的新闻"""

    # 1.取参数
    other_id = request.args.get('user_id')
    page = request.args.get('p', 1)

    # 2.判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

    if not other:
        return jsonify(errno=RET.NODATA, errmsg='当前用户不存在')

    try:
        paginate = other.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')
    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        'news_list': news_dict_li,
        'total_page': total_page,
        'current_page': current_page
    }
    return jsonify(errno='RET.OK', errmsg='OK', data=data)


# 实现关注我的用户的信息查询显示
@profile_blue.route('/other_info')
@user_login_data
def other_info():
    user = g.user

    # 去查询其他人的用户信息
    other_id = request.args.get('user_id')

    if not other_id:
        abort(404)

    # 查询指定id的用户信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    is_followed = False
    # if 当前新闻有作者，并且当前登录用户已关注过这个用户
    if other and user:
        # if user 是否关注过news.user
        if other in user.followed:
            is_followed = True

    data = {
        'is_followed': is_followed,
        'user': g.user.to_dict() if g.user else None,
        'other_info': other.to_dict()
    }
    return render_template('news/other.html', data=data)


# 实现用户我的关注页面
@profile_blue.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    totall_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        totall_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {
        'users': user_dict_li,
        'total_page': totall_page,
        'current_page': current_page
    }
    return render_template('news/user_follow.html', data=data)


# 实现用户新闻列表页面
@profile_blue.route('/news_list')
@user_login_data
def user_news_list():

    # 查询新闻数据　－－> 需要自己的ID
    page = request.args.get('p', 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='页码错误')

    user = g.user
    news_model_list = []
    current_page = 1
    total_page = 1

    try:
        paginates = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_model_list = paginates.items
        current_page = paginates.page
        total_page = paginates.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_review_dict())
    data = {
        'news_list': news_dict_li,
        'total_page': total_page,
        'current_page': current_page
    }
    return render_template('news/user_news_list.html', data=data)
        

# 实现用户发布新闻页面
@profile_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def user_news_release():
    if request.method == 'GET':
        # 查询新闻分类
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库错误')
        category_dict_li = []

        for category in categories:
            category_dict_li.append(category.to_dict())
        # 去掉最新的分类数据
        category_dict_li.pop(0)

        data = {
            'categories': category_dict_li
        }
        return render_template('news/user_news_release.html', data=data)

    # POST 请求发布

    # 1.获取要提交的数据
    title = request.form.get('title')

    # 来源
    source = '个人发布'

    # 摘要
    digest = request.form.get('digest')
    content = request.form.get('content')
    index_image = request.files.get('index_image')
    category_id = request.form.get('category_id')

    if not all([digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    # TODO:对分类ID --> int --> 查询数据库看是否有这个ID

    # 添加图片
    try:
        index_image_data = index_image.read()
        image_file_name = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片失败')
    # 添加到数据库
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    # 如果图片是别人网站的数据，尅加上其他网站的前缀，不加也行
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_file_name
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    return jsonify(errno=RET.OK, errmsg='OK')


# 实现个人中心收藏新闻页面
@profile_blue.route('/collection')
@user_login_data
def user_collection():
    # 获取页数
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    user = g.user
    collections = []
    current_page = 1
    total_page = 1

    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)

        # 获取分页数据
        collections =paginate.items

        # 获取当前页
        current_page = paginate.page

        # 获取总页数
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
    # 收藏列表
    collections_dict_li = []
    for news in collections:
        collections_dict_li.append(news.to_basic_dict())

    data = {
        'total_page': total_page,
        'current_page': current_page,
        'collections': collections_dict_li
    }
    return render_template('news/user_collection.html', data=data)


# 实现个人中心修改密码页面
@profile_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    # 1.获取到传入参数
    data_dict = request.json
    old_password = data_dict.get('old_password')
    new_password = data_dict.get('new_password')

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    # 2.获取当前登录的用户信息
    user = g.user

    # 3.对比旧密码是否正确
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR, errmsg='密码输入错误')

    # 4.设置新密码
    user.password = new_password

    return jsonify(errno=RET.OK, errmsg='OK')


# 实现个人中心上传图片页面
@profile_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_pic_info.html', data=data)
    # POST请求
    # 1.获取图像信息
    try:
        avatar_data = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 2.上传图像到云服务器中（七牛云）
    try:
        avatar_file_name = storage(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='第三方错误')

    # 3.将文件名存储到数据库中-->只需要记录文件名
    user.avatar_url = avatar_file_name

    data = {

        "avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_file_name
    }

    # 4.将图像的url地址返回给前端
    return jsonify(errno=RET.OK, errmsg='OK', data=data)


# 实现个人中心基本信息页面
@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    if request.method == 'GET':
        user = g.user

        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    # POST请求
    # 1.获取参数
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')

    # 2.校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if gender not in['MAN', 'WOMEN']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 3.设置用户模型
    user = g.user
    user.gender = gender
    user.signature = signature
    user.nick_name = nick_name
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    # 需要更新session信息
    session['nick_name'] = nick_name
    return jsonify(errno=RET.OK, errmsg='OK')


# 实现个人中心主页面
@profile_blue.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user': g.user.to_dict()
    }
    return render_template('news/user.html', data=data)
